package com.sydsen.imager.painter;

import com.sydsen.imager.Canvas;
import com.sydsen.imager.elements.Element;

import java.awt.*;

/**
 * @Auther: syh
 * @Date: 2021/11/1
 * @Description:
 */
public abstract class AbstractPainter<T extends Element<T>> implements IPainter<T> {

    @Override
    public void draw(Canvas canvas, T element) throws Exception {
        if (element.center()) {
            int centerX = (canvas.getWidth() - getElementWidth(element)) / 2;
            element.x(centerX);
        }

        if (element.middle()) {
            int middleY = (canvas.getHeight() - getElementHeight(element)) / 2;
            element.y(middleY);
        }

        // 旋转
        if (element.rotate() != 0) {
            canvas.getGraphics().rotate(Math.toRadians(element.rotate()),
                            element.x() + element.width() / 2, element.y() + element.height() / 2);
        }

        //设置透明度
        canvas.getGraphics()
                .setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, element.alpha()));


        doDraw(canvas, element);

        //绘制完后反向旋转，以免影响后续元素
        if (element.rotate() != 0) {
            canvas.getGraphics().rotate(-Math.toRadians(element.rotate()),
                    element.x() + element.width() / 2, element.y() + element.height() / 2);
        }
    }

    protected int getElementHeight(T element) {
        return element.height();
    }

    protected int getElementWidth(T element) {
        return element.width();
    }

    protected abstract void doDraw(Canvas canvas, T element) throws Exception;
}
